package com.api.customization.huangwm.dao.SW003;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.customization.huangwm.utils.DBTools;
import com.customization.huangwm.utils.DateTools;
import com.customization.huangwm.utils.LogTool;
import org.apache.commons.lang.StringEscapeUtils;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.system.SysRemindWorkflow;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author Huangwm
 * @Date 2023-10-07
 * @Version 1.0
 * @Description TODO 采购入库及退库接口改造
 **/
public class PurchaseStorageDao extends BaseBean{
    private LogTool log = new LogTool("/log/SW003/huangwm/dao/PurchaseStorageDao", false);
    private DBTools dbTools = new DBTools();
    public final String assetTable = "uf_003_AssteInfo";
    public final String tableKey = "assetCode";
    private LoggingDao loggingDao = new LoggingDao();
    private DateTools dateTools = new DateTools();
    private String apiPath = "/api/customization/SW003/assetOperation";
    private AssetInfoOperationDao mainDao = new AssetInfoOperationDao();

    /**
     * 采購入庫 isAsset為Y时插入到采購入庫記錄，為N时將數量更新到物料表庫存中並記錄日志，同時也徐插入采購入庫記錄
     * @param requestParams
     * @return
     */
    public Map<String, Object> purchaseStorageV2(Map<String, Object> requestParams) throws Exception {
        Map<String, Object> result = new HashMap<>();
        result.put("apiStatus", true);
        result.put("msg", "初始信息、成功請忽略");
        log.writeLog("采購入庫參數----");
        log.writeLog(JSONObject.toJSONString(requestParams));
        if (!requestParams.containsKey("datas")) {
            result.put("msg", "采購入庫缺少必要参数datas");
            result.put("apiStatus", false);
            loggingDao.wrtieLog("1", apiPath + "/purchaseStorageV2", JSON.toJSONString(requestParams), JSON.toJSONString(result));
            return result;
        }
        String billid = "";
        if (!requestParams.containsKey("billid")) {
            result.put("msg", "采購入庫缺少必要参数billid");
            result.put("apiStatus", false);
            loggingDao.wrtieLog("1", apiPath + "/purchaseStorageV2", JSON.toJSONString(requestParams), JSON.toJSONString(result));
            return result;
        }
        billid = StringEscapeUtils.unescapeJava((String) requestParams.get("billid"));
        if (billid.isEmpty()) {
            result.put("msg", "采購入庫参数billid為空請檢查");
            result.put("apiStatus", false);
            return result;
        }
        billid = "CGRK-"+billid;
        String poNo = "";
        if (!requestParams.containsKey("poNo")) {
            result.put("msg", "采購入庫缺少必要参数poNo");
            result.put("apiStatus", false);
            loggingDao.wrtieLog("1", apiPath + "/purchaseStorageV2", JSON.toJSONString(requestParams), JSON.toJSONString(result));
            return result;
        }
        //poNo = String.valueOf(requestParams.get("poNo")).replace("\"","");
        poNo = StringEscapeUtils.unescapeJava((String) requestParams.get("poNo"));
        if (poNo.isEmpty()) {
            result.put("msg", "采購入庫参数poNo為空請檢查");
            result.put("apiStatus", false);
            return result;
        }
        String prTable = getPropValue("SW003","prTable");
        if(prTable.isEmpty()){
            result.put("msg", "获取SW003.properties中的prTable为空");
            result.put("apiStatus", false);
            loggingDao.wrtieLog("1", apiPath + "/purchaseStorageV2", JSON.toJSONString(requestParams), JSON.toJSONString(result));
            return result;
        }

        String uf_003_WareHouseNum_Modeid = new BaseBean().getPropValue("SW003", "uf_003_WareHouseNum_Modeid");
        if(uf_003_WareHouseNum_Modeid.isEmpty()){
            result.put("msg", "配置文件SW003.peoperties中缺少uf_003_WareHouseNum_Modeid配置項");
            result.put("apiStatus", false);
            loggingDao.wrtieLog("1", apiPath + "/purchaseStorageV2", JSON.toJSONString(requestParams), JSON.toJSONString(result));
            return result;
        }

        List<Map<String, String>> datas = new ArrayList<>();
        try {
            //datas = (List<Map<String, String>>)  requestParams.get("datas");
            datas = (List<Map<String, String>>) JSONObject.parse(requestParams.get("datas").toString());
        } catch (Exception e) {
            e.printStackTrace();
            result.put("msg", "從參數中轉化datas異常 " + e.getMessage());
            result.put("apiStatus", false);
            loggingDao.wrtieLog("1", apiPath + "/purchaseStorageV2", JSON.toJSONString(requestParams), JSON.toJSONString(result));
            return result;
        }

        Map<String, Object> check = mainDao.checkDetails(datas);
        boolean checkResult = (boolean) check.get("apiStatus");
        if (!checkResult) {
            result.put("msg", "檢查物料信息參數失敗 " + check.get("msg"));
            result.put("apiStatus", false);
            loggingDao.wrtieLog("1", apiPath + "/purchaseStorageV2", JSON.toJSONString(requestParams), JSON.toJSONString(result));
            return result;
        }
        String uf_003_yyArrivalRecord_Modeid = getPropValue("SW003", "uf_003_yyArrivalRecord_Modeid");

        String martix = getPropValue("SW003", "martix");

        String sql_0 = "insert into uf_003_yyArrivalRecord"
                + "(formmodeid,modedatacreater,modedatacreatertype,modedatacreatedate,modedatacreatetime,MODEUUID"
                + ",eapItemCode,itemcode,assetName,assetDescribe,unit,isAsset,manageDep,assetModel,assetType,quantity,locationCode,locationDescribe"
                + ",brand,manufacturer,FACode,FACategory,prjNo,poCode,price,arrivalDate,supplier,assetNums,thisSouce,prid,dateStr,wereHouse,currency," +
                "params_id,detail_id)"
                + "values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";

        String sql_1 = "update " + assetTable + " set totalQuantity=totalQuantity + ?,InventoryQuantity=InventoryQuantity + ? where " + tableKey + "=?";

        List<List<Object>> paramsList_0 = new ArrayList<>();//是资产的数据插入
        List<List<Object>> paramsList_1 = new ArrayList<>();//不是资产的数据插入
        List<Map<String, String>> logList = new ArrayList<>();//日志记录
        RecordSet newRs = new RecordSet();
        RecordSet get = new RecordSet();
        RecordSetTrans set = new RecordSetTrans();
        set.setAutoCommit(false);

        //生成仓库库存记录sql
        String insertWarehouse = "insert into uf_003_WarehouseNum" +
                "(formmodeid,modedatacreater,modedatacreatertype,modedatacreatedate,modedatacreatetime,MODEUUID"+
                ",assetCode,wareHouse,num1,num2,num3,num4) " +
                "values(?,?,?,?,?,?,?,?,?,?,?,?)";

        //2023年9月1日 优化采购入库时没有仓库记录，但是同个物料有多条采购入库记录导致生成多条仓库库存记录的问题
        List<String> allCode = new ArrayList<>();
        List<String> allDetailid = new ArrayList<>();
        for (Map<String, String> data : datas) {
            String assetCode = data.get("assetCode").trim();
            if(!data.containsKey("detailid")){
                result.put("msg", "itemcode["+assetCode+"]未找到detailid参数");
                result.put("apiStatus", false);
                loggingDao.wrtieLog("1", apiPath + "/purchaseStorageV2", JSON.toJSONString(requestParams), JSON.toJSONString(result));
                return result;
            }
            String detail_id = data.get("detailid");
            detail_id = "CGRK-"+detail_id;
            if(detail_id.isEmpty()){
                result.put("msg", "itemcode["+assetCode+"]未对应detailid为空");
                result.put("apiStatus", false);
                loggingDao.wrtieLog("1", apiPath + "/purchaseStorageV2", JSON.toJSONString(requestParams), JSON.toJSONString(result));
                return result;
            }
            //检查参数是否包含prid
            if(!data.containsKey("prid")){
                result.put("msg", "itemcode["+assetCode+"]未找到prid参数");
                result.put("apiStatus", false);
                loggingDao.wrtieLog("1", apiPath + "/purchaseStorageV2", JSON.toJSONString(requestParams), JSON.toJSONString(result));
                return result;
            }
            if(!allCode.contains(assetCode)){
                allCode.add(assetCode);
            }
            if(!allDetailid.contains(detail_id)){
                allDetailid.add(detail_id);
            }
        }

        //先判断code是否有仓库记录，没有则先插入数量为0的
        RecordSet is = new RecordSet();//用非事务直接写入数据
        for(String assetCode : allCode ){
            Map<String,String> assetInfo = dbTools.getAssetAllFieldoByCode(newRs,assetCode);
            log.writeLog("assetInfo>>"+JSONObject.toJSONString(assetInfo));
            log.writeLog("warehouse>>"+assetInfo.get("warehouse"));
            //沒有倉庫記錄  插入
            String itemid = assetInfo.get("id");//物料数据id
            Map<String, String> prInfo = null;
            String prid = "";
            for(Map<String,String> map :datas){
                //获取该assetCode的prid
                if(map.get("assetCode").equals(assetCode)){
                    prid = map.get("prid").replace("\"","");
                    break;
                }
            }
            //获取pr流程信息
            if(!prid.isEmpty()){
                RecordSet checkPR = new RecordSet();
                checkPR.execute("select requestid,id from "+prTable+" where requestid="+prid);
                log.writeLog("select requestid,id from "+prTable+" where requestid="+prid);
                if(checkPR.next()){
                    prInfo = mainDao.getField1ByPrid(prid,prTable,itemid);
                }
            }
            log.writeLog("prInfo>>"+JSONObject.toJSONString(prInfo));
            //20221019 增加倉庫邏輯 采購入庫時根據pr中的倉庫進行倉庫庫存增加 如果没有prid(或prinfo为空)获取默认仓库
            String wareHouse = (prid.isEmpty() || prInfo == null) ? assetInfo.get("warehouse") : prInfo.get("field1"); //存的是仓库id
            wareHouse = wareHouse.isEmpty() ? assetInfo.get("warehouse") : wareHouse;
            if(wareHouse.isEmpty()){
                set.rollback();
                result.put("msg", "itemcode["+assetCode+"]采購入庫查詢倉庫庫存失敗-->未查询到PR["+prid+"]倉庫(EAP未維護默認倉庫或code與EAP的PR單中不一致):"+wareHouse);
                result.put("apiStatus", false);
                loggingDao.wrtieLog("1", apiPath + "/purchaseStorageV2", JSON.toJSONString(requestParams), JSON.toJSONString(result));
                return result;
            }

            String sql = "select * from uf_003_WarehouseNum where assetCode="+assetInfo.get("id")+" and wareHouse="+wareHouse;
            log.writeLog("判断是否有仓库 "+sql);
            if(get.execute(sql) && get.next()){
                log.writeLog("accetcode："+assetCode+"有仓库");
            }else{
                String modedatacreatedate = dateTools.getCurrentDate();
                String modedatacreatetime = dateTools.getCurrentTime();
                String uuid = dateTools.getUUID();

                //预先插入0数量的仓库记录
                Object[] objects = new Object[]{
                        uf_003_WareHouseNum_Modeid, 1, 0, modedatacreatedate, modedatacreatetime, uuid,
                        assetInfo.get("id"),wareHouse,0,0,0,0
                };
                log.writeLog("无倉庫庫存-插入倉庫數據參數");
                log.writeLog(JSONObject.toJSONString(objects));
                boolean f = is.executeUpdate(insertWarehouse,objects);
                if(!f){
                    result.put("msg", "itemcode["+assetCode+"]生成新倉庫庫存記錄失敗");
                    result.put("apiStatus", false);
                    loggingDao.wrtieLog("1", apiPath + "/purchaseStorageV2", JSON.toJSONString(requestParams), JSON.toJSONString(result));
                    return result;
                }
            }
        }

        //2023年9月27日改 处理差异数据
        //先根据billid查询OA中是否存在记录
        //List<String> histryid1 = getHistryid1(billid);
        List<String> histryid2 = getHistryid2CGRK(billid);
        RecordSet checkPO = new RecordSet();
        RecordSet checkNums = new RecordSet();
        if(histryid2.size()>0){
            //备份 用于获取最终的差异detial_id
            List<String> bakDetilsid = allDetailid;//当前的数据
            List<String> bakHistryid2 = histryid2;

            List<String> subList2 = bakHistryid2.stream().filter(p -> bakDetilsid.contains((String) p)).collect(Collectors.toList());
            bakDetilsid.removeAll(subList2);
            bakHistryid2.removeAll(subList2);
            bakDetilsid.addAll(bakHistryid2);//差异数据，包含了新数据

            for(String detail_id : bakDetilsid){
                log.writeLog("存在差异数据，detailid："+detail_id);
                //根据detail_id查询采购入库记录,如果存在则退库后删除记录
                checkPO.execute("select id,eapitemcode,itemcode,assetNums,quantity  from uf_003_yyArrivalRecord where detail_id='"+detail_id+"'");
                if(checkPO.next()){
                    log.writeLog("根据detail_id查询采购入库记录存在,退库后删除记录");
                    String itemid = checkPO.getString("eapitemcode");//物料数据id
                    Double assetNums = checkPO.getDouble("assetNums");//已登記的資產數量
                    Double _quantity = checkPO.getDouble("quantity");//采購入庫數量
                    int recordId = checkPO.getInt("id");

                    Map<String,String> assetInfo  = dbTools.getAssetAllFieldoByID(newRs,itemid);
                    String assetCode = assetInfo.get("assetcode");

                    Map<String, String> prInfo = null;
                    String prid = "";
                    for(Map<String,String> map :datas){
                        //获取该assetCode的prid
                        if(map.get("assetCode").equals(assetCode)){
                            prid = map.get("prid").replace("\"","");
                            break;
                        }
                    }
                    //获取pr信息中的仓库
                    if(!prid.isEmpty()){
                        RecordSet checkPR = new RecordSet();
                        checkPR.execute("select requestid,id from "+prTable+" where requestid="+prid);
                        log.writeLog("select requestid,id from "+prTable+" where requestid="+prid);
                        if(checkPR.next()){
                            prInfo = mainDao.getField1ByPrid(prid,prTable,itemid);
                        }
                    }
                    String wareHouse = (prid.isEmpty() || prInfo == null)  ? assetInfo.get("warehouse") : prInfo.get("field1") ;//存的是倉庫id
                    wareHouse = wareHouse.isEmpty() ? assetInfo.get("warehouse") : wareHouse;
                    //刪除入庫記錄--先插入
                    String insertSql = "insert into uf_003_Arrival_del(oldid,eapItemCode,itemcode,assetDescribe,isAsset,quantity,assetModel,manageDep,assetType,locationCode,\n" +
                            "locationDescribe,brand,manufacturer,FACode,FACategory,prjNo,poCode,price,arrivalDate,supplier,thisSouce,assetNums,assetName)\n" +
                            "select id,eapItemCode,itemcode,assetDescribe,isAsset,quantity,assetModel,manageDep,assetType,locationCode,\n" +
                            "locationDescribe,brand,manufacturer,FACode,FACategory,prjNo,poCode,price,arrivalDate,supplier,thisSouce,assetNums,assetName\n" +
                            "from uf_003_yyArrivalRecord where id=" + recordId;
                    set.execute(insertSql);
                    boolean d1 =  set.execute("delete from uf_003_yyArrivalRecord where id=" + recordId);
                    log.writeLog("刪除入庫記錄 "+d1);

                    //減少物料表中的庫存數量
                    String s1 = "update " + assetTable + " set totalQuantity=totalQuantity-"+_quantity+",InventoryQuantity=InventoryQuantity-"+_quantity+" where id="+itemid;
                    log.writeLog("處理差异数据-減少物料表中的庫存數量："+s1);
                    boolean r1 = set.execute(s1);
                    log.writeLog("结果1："+r1);

                    //更新倉庫庫存--減少庫存
//                String s2 = "update uf_003_WarehouseNum set num1=num1-("+_quantity+"),num3=num3-("+_quantity+") where assetCode="+itemid+" and wareHouse="+wareHouse;
//                log.writeLog("删除差异数据-减少仓库库存数量："+s2);
//                boolean r2 =set.execute(s2);
//                log.writeLog("结果2："+r2);
                    String sql = "select * from uf_003_WarehouseNum where assetCode="+assetInfo.get("id")+" and wareHouse="+wareHouse;
                    if(get.execute(sql) && get.next()){
                        String wid = get.getString("id");
                        String s = "update uf_003_WarehouseNum set num1=num1 - ("+_quantity+"),num3=num3-("+_quantity+") where id="+wid;
                        log.writeLog("處理差异数据-更新倉庫庫存 "+s);
                        boolean f = set.execute(s);
                        log.writeLog("更新結果 "+f);
                        if(!f){
                            set.rollback();
                            result.put("msg", "itemcode["+assetCode+"]采購入庫更新倉庫庫存失敗");
                            result.put("apiStatus", false);
                            loggingDao.wrtieLog("1", apiPath + "/purchaseStorageV2", JSON.toJSONString(requestParams), JSON.toJSONString(result));
                            return result;
                        }
                    }else {
                        set.rollback();
                        result.put("msg", "itemcode["+assetCode+"]采購入庫查詢倉庫庫存失敗-->EAP未查询到倉庫记录:"+wareHouse);
                        result.put("apiStatus", false);
                        loggingDao.wrtieLog("1", apiPath + "/purchaseStorageV2", JSON.toJSONString(requestParams), JSON.toJSONString(result));
                        return result;
                    }
                    //刪除出入庫記錄
                    boolean d2 = set.execute("delete from uf_003_inventoryLog where detail_id='" + detail_id+"'");
                    log.writeLog("刪除出入庫記錄 "+d2);

                    if(assetNums>0){
                        //有登记资产 发起提醒给到管理部门负责人
                        String  manageDep = assetInfo.get("managedep");
                        get.execute(" select depmanager from "+martix +" where depid="+manageDep);
                        get.next();
                        String depManager = get.getString("depmanager");
                        log.writeLog("有登记资产 发起提醒给到管理部门负责人>"+depManager);
                        SysRemindWorkflow remind = new SysRemindWorkflow();
                        remind.make("采購入庫退庫資產處理提醒 "+assetCode,
                                0, 0, 0, 0, 1,
                                depManager+",1",
                                "<span> item code為["+assetCode+"]存在采購入庫的數據已登記資產(已登記數量"+assetNums+"),請在系統中做相關處理", 0);
                    }

                }
                log.writeLog("差異數據處理完成 detail_id："+detail_id);
            }
        }

        for (Map<String, String> data : datas) {
            log.writeLog("處理接口明細數據");
            List<Object> param_0 = new ArrayList<>();
            List<Object> param_1 = new ArrayList<>();
            String detail_id = data.get("detailid");
            String assetCode = data.get("assetCode").trim();
            Map<String,String> assetInfo = dbTools.getAssetAllFieldoByCode(newRs,assetCode);
            log.writeLog("assetInfo:"+JSONObject.toJSONString(assetInfo));
            String assetName = assetInfo.get("assetname"),
                    assetDescribe = assetInfo.get("assetdescribe"),
                    unit = assetInfo.get("unit"),
                    manageDep = assetInfo.get("managedep"),
                    assetModel = assetInfo.get("assetmodel"),
                    assetType = assetInfo.get("assettype");
            //数量有可能负数
            Double quantity = Double.parseDouble(data.getOrDefault("quantity", "0"));
            String  locationCode = data.get("locationCode"),
                    locationDescribe = data.get("locationDescribe"),
                    brand = data.get("brand"),
                    manufacturer = data.get("manufacturer"),
                    FACode = data.get("FACode"),
                    FACategory = data.get("FACategory"),
                    prjNo = data.get("prjNo"),
                    price = data.get("price"),
                    arrivalDate = data.get("arrivalDate"),
                    supplier = data.get("supplier"),
                    currency = data.getOrDefault("currency","");
            int isAsset = mainDao.getIsAsset(assetCode, "isAsset");//判断是否為资产
            String itemid = assetInfo.get("id");//物料数据id
            Map<String, String> prInfo = null ;
            String prid = data.get("prid");
            if(!prid.isEmpty()){
                prInfo = mainDao.getField1ByPrid(prid,prTable,itemid);
            }
            log.writeLog("prid:"+prid);
            log.writeLog("prinfo:"+JSONObject.toJSONString(prInfo));
            //20221019 增加倉庫邏輯 采購入庫時根據pr中的倉庫進行倉庫庫存增加 如果没有prid(或pr信息获取为空)则获取默认仓库
            String wareHouse = (prid.isEmpty() || prInfo == null ) ? assetInfo.get("warehouse") :prInfo.get("field1") ;//存的是倉庫id
            wareHouse = wareHouse.isEmpty() ? assetInfo.get("warehouse") : wareHouse;
            if(wareHouse.isEmpty()){
                result.put("msg", "itemcode["+assetCode+"]采購入庫查詢倉庫庫存失敗-->未查询到PR["+prid+"]倉庫或EAP未維護默認倉庫:"+wareHouse);
                result.put("apiStatus", false);
                loggingDao.wrtieLog("1", apiPath + "/purchaseStorageV2", JSON.toJSONString(requestParams), JSON.toJSONString(result));
                return result;
            }
            //2023年9月28日改
            //根据detail_id查询采购入库记录,如果存在则判断两次数量差异，不存在走原本逻辑
            detail_id = "CGRK-"+detail_id;
            checkPO.execute("select id,assetNums,quantity from uf_003_yyArrivalRecord where detail_id='"+detail_id+"'");
            if(checkPO.next()){
                Double assetNums = checkPO.getDouble("assetNums");//已登記的資產數量
                Double _quantity = checkPO.getDouble("quantity");//采購入庫數量
                int recordId = checkPO.getInt("id");
                if(quantity<assetNums){
                    if(isAsset==0){
                        //資產物料 当前采购入库数量 小于已登记的资产数量 发出提醒
                        get.execute(" select depmanager from "+martix +" where depid="+manageDep);
                        get.next();
                        String depManager = get.getString("depmanager");

                        log.writeLog("有登记资产 发起提醒给到管理部门负责人>"+depManager);
                        SysRemindWorkflow remind = new SysRemindWorkflow();
                        remind.make("采購入庫退庫資產處理提醒 "+assetCode,
                                0, 0, 0, 0, 1,
                                depManager+",1",
                                "<span> item code為["+assetCode+"]存在采購入庫的數據已登記資產(已登記數量"+assetNums+"),請在系統中做相關處理", 0);
                    }

                    String upSql = "update uf_003_yyArrivalRecord set quantity="+quantity+" where id="+recordId;
                    log.writeLog("当前入库数量小於已等級的資產数量 更新uf_003_yyArrivalRecord表中的_quantity>> "+upSql);
                    boolean r1 = set.execute(upSql);
                    log.writeLog("更新結果 "+r1);

                }else{
                    //判断上一次的采购入库数量和本次入库数量
                    if(quantity>_quantity){
                        String upSql = "update uf_003_yyArrivalRecord set quantity="+quantity+" where id="+recordId;
                        log.writeLog("当前入库数量大于上一次的记录数量 更新uf_003_yyArrivalRecord表中的_quantity>> "+upSql);
                        boolean r1 = set.execute(upSql);
                        log.writeLog("更新結果 "+r1);
                    }else if(quantity<_quantity){
                        String upSql = "update uf_003_yyArrivalRecord set quantity="+quantity+" where id="+recordId;
                        log.writeLog("当前入库数量小于上一次的记录数量 更新uf_003_yyArrivalRecord表中的_quantity>> "+upSql);
                        boolean r2 = set.execute(upSql);
                        log.writeLog("更新結果 "+r2);
                    }
                }

            }else{
                //------分割綫
                param_0.add(uf_003_yyArrivalRecord_Modeid);
                param_0.add(1);
                param_0.add(0);
                param_0.add(dateTools.getCurrentDate());
                param_0.add(dateTools.getCurrentTime());
                param_0.add(dateTools.getUUID());
                param_0.add(mainDao.getIsAsset(assetCode, "id"));
                param_0.add(assetCode);
                param_0.add(assetName);
                param_0.add(assetDescribe);
                //param_0.add(getAssetUnit(unit));
                param_0.add(unit);
                param_0.add(isAsset);
                //param_0.add(getManageDep(assetCode, "manageDep"));
                param_0.add(manageDep);
                param_0.add(assetModel);
                //param_0.add(getAssetType(assetType));
                param_0.add(assetType);
                param_0.add(quantity);
                param_0.add(locationCode);
                param_0.add(locationDescribe);
                param_0.add(brand);
                param_0.add(manufacturer);
                param_0.add(FACode);
                param_0.add(FACategory);
                param_0.add(prjNo);
                param_0.add(poNo.replace("\"",""));
                param_0.add(price);
                param_0.add(arrivalDate.replace("/", "-"));
                param_0.add(supplier);
                param_0.add(0);
                param_0.add(2);
                param_0.add(prid);
                param_0.add(dateTools.getCurrentDate());
                param_0.add(wareHouse);
                param_0.add(currency);//2023年8月25日 增加币种
                param_0.add(billid);//2023年10月7日增加
                param_0.add(detail_id);//2023年10月7日增加
                paramsList_0.add(param_0);
                //------分割綫
            }

            //根据detail_id查询出入库记录,如果存在则判断两次数量差异，不存在走原本逻辑(逻辑已在上面处理 这里只需要判断更新库存)
            checkNums.execute("select id,assetCode,quantity from uf_003_inventoryLog where detail_id='"+detail_id+"'");
            if(checkNums.next()){
                Double thisquantity = checkNums.getDouble("quantity");
                int recordId = checkNums.getInt("id");
                if(thisquantity!=quantity){
                    String s1 = "update uf_003_inventoryLog set quantity="+quantity+" where id="+recordId;
                    log.writeLog("更新出入庫記錄 "+s1);
                    boolean r1 = set.execute(s1);
                    log.writeLog("更新結果 "+r1);

                    //更新倉庫庫存--根據thisquantity和quantity的差額
                    Double chae = quantity-thisquantity;//為負數時需要減少倉庫庫存 正數則增加
                    String sql = "select * from uf_003_WarehouseNum where assetCode="+assetInfo.get("id")+" and wareHouse="+wareHouse;
                    if(get.execute(sql) && get.next()){
                        String wid = get.getString("id");
                        String sql1 = "";
                        String sql2 = "";
                        if(chae>0){
                            sql1 = "update uf_003_WarehouseNum set num1=num1 + "+chae+",num3=num3 + "+chae+" where id="+wid;
                            sql2 = "update " + assetTable + " set totalQuantity=totalQuantity+"+chae+",InventoryQuantity=InventoryQuantity+"+chae+" where id="+itemid;
                        }else{
                            sql1 = "update uf_003_WarehouseNum set num1=num1 - "+Math.abs(chae)+",num3=num3 - "+Math.abs(chae)+" where id="+wid;
                            sql2 = "update " + assetTable + " set totalQuantity=totalQuantity-"+Math.abs(chae)+",InventoryQuantity=InventoryQuantity-"+Math.abs(chae)+" where id="+itemid;
                        }

                        log.writeLog("有倉庫庫存-更新倉庫庫存 "+sql1);
                        boolean f1 = set.execute(sql1);
                        log.writeLog("結果1 "+f1);

                        //減少物料表中的庫存數量
                        log.writeLog("删除差异数据-減少物料表中的庫存數量："+sql2);
                        boolean f2 = set.execute(sql2);
                        log.writeLog("结果2："+f2);

                        if(!f1 || !f2){
                            set.rollback();
                            result.put("msg", "itemcode["+assetCode+"]采購入庫更新倉庫庫存失敗");
                            result.put("apiStatus", false);
                            loggingDao.wrtieLog("1", apiPath + "/purchaseStorageV2", JSON.toJSONString(requestParams), JSON.toJSONString(result));
                            return result;
                        }
                    }else {
                        set.rollback();
                        result.put("msg", "itemcode["+assetCode+"]采購入庫查詢倉庫庫存失敗-->EAP未查询到倉庫记录:"+wareHouse);
                        result.put("apiStatus", false);
                        loggingDao.wrtieLog("1", apiPath + "/purchaseStorageV2", JSON.toJSONString(requestParams), JSON.toJSONString(result));
                        return result;
                    }
                }
            }else{
                //出入库日志
                Map<String, String> logMap = new HashMap();
                logMap.put("assetCode", assetCode);
                logMap.put("assetName", assetName);
                logMap.put("quantity", String.valueOf(Math.abs(quantity)));
                logMap.put("requestNumber", poNo.replace("\"",""));
                logMap.put("reason", "采購入庫");
                logMap.put("field1", wareHouse);
                logMap.put("field2", prInfo == null ? "" : prInfo.get("field2"));
                logMap.put("detail_id",detail_id);
                logList.add(logMap);
                //入庫
                param_1.add(quantity);
                param_1.add(quantity);
                param_1.add(assetCode);
                paramsList_1.add(param_1);

                //更新倉庫庫存--新增庫存
                String sql = "select * from uf_003_WarehouseNum where assetCode="+assetInfo.get("id")+" and wareHouse="+wareHouse;
                if(get.execute(sql) && get.next()){
                    String wid = get.getString("id");
                    String s = "update uf_003_WarehouseNum set num1=num1 + "+quantity+",num3=num3 + "+quantity+" where id="+wid;
                    log.writeLog("有倉庫庫存-更新倉庫庫存 "+s);
                    boolean f = set.execute(s);
                    log.writeLog("更新結果 "+f);
                    if(!f){
                        set.rollback();
                        result.put("msg", "itemcode["+assetCode+"]采購入庫更新倉庫庫存失敗");
                        result.put("apiStatus", false);
                        loggingDao.wrtieLog("1", apiPath + "/purchaseStorageV2", JSON.toJSONString(requestParams), JSON.toJSONString(result));
                        return result;
                    }
                }else {
                    set.rollback();
                    result.put("msg", "itemcode["+assetCode+"]采購入庫查詢倉庫庫存失敗-->EAP未查询到倉庫记录:"+wareHouse);
                    result.put("apiStatus", false);
                    loggingDao.wrtieLog("1", apiPath + "/purchaseStorageV2", JSON.toJSONString(requestParams), JSON.toJSONString(result));
                    return result;
                }
            }
        }
        //寫入數據
        if (paramsList_0.size() > 0) {
            log.writeLog(sql_0);
            log.writeLog(JSONObject.toJSONString(paramsList_0));
            try {
                set.executeBatchSql(sql_0, paramsList_0);
            } catch (Exception e) {
                set.rollback();
                result.put("msg", "資產物料采購入庫執行SQL異常 \n" + e.getMessage());
                result.put("apiStatus", false);
                loggingDao.wrtieLog("1", apiPath + "/purchaseStorageV2", JSON.toJSONString(requestParams), JSON.toJSONString(result));
                return result;
            }
        }
        if (paramsList_1.size() > 0) {
            log.writeLog(sql_1);
            log.writeLog(JSONObject.toJSONString(paramsList_1));
            try {
                set.executeBatchSql(sql_1, paramsList_1);
            } catch (Exception e) {
                set.rollback();
                result.put("msg", "非資產物料采購入庫執行SQL異常 \n" + e.getMessage());
                result.put("apiStatus", false);
                loggingDao.wrtieLog("1", apiPath + "/purchaseStorageV2", JSON.toJSONString(requestParams), JSON.toJSONString(result));
                return result;
            }
        }
        try{
            loggingDao.wrtieLog("1", apiPath + "/purchaseStorageV2", JSON.toJSONString(requestParams), JSON.toJSONString(result));
            for (int i = 0; i < logList.size(); i++) {
                Map<String, String> log = logList.get(i);
                loggingDao.wrtieInventoryLog(set,"1", log.get("assetCode"),
                        Double.parseDouble(log.get("quantity")), log.get("requestNumber"),
                        log.get("reason"),log.get("field1"),log.get("field2"),
                        "2","","",log.get("assetName"),billid,log.get("detail_id"));
            }
        }catch (Exception e){
            set.rollback();
            result.put("msg", "物料采購入庫最终记录日志异常 \n" + e.getMessage());
            result.put("apiStatus", false);
            return result;
        }

        log.writeLog("权限重构开始=>>>" + dateTools.getCurrentTimes());
        RecordSet getMaxid = new RecordSet();
        getMaxid.execute("select max(id) as maxid from " + assetTable);
        getMaxid.next();
        int maxid = getMaxid.getInt("maxid");
        for (int i = maxid; i > maxid - paramsList_0.size(); i--) {
            dbTools.refreshRight(1, Util.getIntValue(uf_003_yyArrivalRecord_Modeid, 0), i);
        }
        log.writeLog("权限重构结束=>>>" + dateTools.getCurrentTimes());

        set.commit();
        return result;
    }



    /**
     * 采購退貨 isAsset為Y时檢查對應記錄是否登記了資產，如已登記數量不足扣減返回提示需要在EAP走報廢，
     * 為N時查詢物料表剩餘庫存是否足夠扣，剩餘足夠扣減時減少庫存並生成出庫記錄，不足時返回提示需要在EAP進行歸還
     * @param requestParams
     * @return
     */
    public Map<String, Object> purchaseStorageReturnV2(Map<String, Object> requestParams) throws Exception {
        Map<String, Object> result = new HashMap<>();
        result.put("apiStatus", true);
        result.put("msg", "初始信息、成功請忽略");
        log.writeLog("采購退貨參數----");
        log.writeLog(JSONObject.toJSONString(requestParams));
        if (!requestParams.containsKey("datas")) {
            result.put("msg", "采購退貨缺少必要参数datas");
            result.put("apiStatus", false);
            loggingDao.wrtieLog("1", apiPath + "/purchaseStorageReturnV2", JSON.toJSONString(requestParams), JSON.toJSONString(result));
            return result;
        }

        String billid = "";
        if (!requestParams.containsKey("billid")) {
            result.put("msg", "采購退貨缺少必要参数billid");
            result.put("apiStatus", false);
            loggingDao.wrtieLog("1", apiPath + "/purchaseStorageReturnV2", JSON.toJSONString(requestParams), JSON.toJSONString(result));
            return result;
        }
        billid = StringEscapeUtils.unescapeJava((String) requestParams.get("billid"));
        if (billid.isEmpty()) {
            result.put("msg", "采購退貨参数billid為空請檢查");
            result.put("apiStatus", false);
            return result;
        }
        billid = "CGTH-"+billid;
        List<Map<String, String>> datas = new ArrayList<>();
        try {
            //datas = (List<Map<String, String>>)  requestParams.get("datas");
            datas = (List<Map<String, String>>) JSONObject.parse(requestParams.get("datas").toString());
        } catch (Exception e) {
            e.printStackTrace();
            result.put("msg", "采購退貨轉化參數datas異常 " + e.getMessage());
            result.put("apiStatus", false);
            loggingDao.wrtieLog("1", apiPath + "/purchaseStorageReturnV2", JSON.toJSONString(requestParams), JSON.toJSONString(result));
            return result;
        }

        Map<String, Object> check1 = mainDao.checkDetails(datas);
        boolean checkResult1 = (boolean) check1.get("apiStatus");
        if (!checkResult1) {
            result.put("msg", "采購退貨檢查物料信息參數失敗 " + check1.get("msg"));
            result.put("apiStatus", false);
            loggingDao.wrtieLog("1", apiPath + "/purchaseStorageReturnV2", JSON.toJSONString(requestParams), JSON.toJSONString(result));
            return result;
        }

        String prTable = getPropValue("SW003","prTable");
        if(prTable.isEmpty()){
            result.put("msg", "获取SW003.properties中的prTable为空");
            result.put("apiStatus", false);
            loggingDao.wrtieLog("1", apiPath + "/purchaseStorageReturnV2", JSON.toJSONString(requestParams), JSON.toJSONString(result));
            return result;
        }

        //2023年10月11日 修改退库逻辑 满足多次调用
        List<String> allDetailid = new ArrayList<>();//所有的dtid

        for (Map<String, String> data : datas) {
            String assetCode = data.get("assetCode").trim();
            if(!data.containsKey("detailid")){
                result.put("msg", "itemcode["+assetCode+"]未找到detailid参数");
                result.put("apiStatus", false);
                loggingDao.wrtieLog("1", apiPath + "/purchaseStorageV2", JSON.toJSONString(requestParams), JSON.toJSONString(result));
                return result;
            }
            String detail_id = data.get("detailid");
            detail_id = "CGTH-"+detail_id;
            if(detail_id.isEmpty()){
                result.put("msg", "itemcode["+assetCode+"]未对应detailid为空");
                result.put("apiStatus", false);
                loggingDao.wrtieLog("1", apiPath + "/purchaseStorageV2", JSON.toJSONString(requestParams), JSON.toJSONString(result));
                return result;
            }
            //检查参数是否包含prid
            if(!data.containsKey("prid")){
                result.put("msg", "itemcode["+assetCode+"]未找到prid参数");
                result.put("apiStatus", false);
                loggingDao.wrtieLog("1", apiPath + "/purchaseStorageV2", JSON.toJSONString(requestParams), JSON.toJSONString(result));
                return result;
            }

            if(!allDetailid.contains(detail_id)){
                allDetailid.add(detail_id);
            }
        }


        //2023年10月11日 新退库中不再校验PO
        /*
        Map<String, Object> check2 = mainDao.checkPO(datas);
        boolean checkResult2 = (boolean) check2.get("apiStatus");
        if (!checkResult2) {
            result.put("msg", "采購退貨檢查PO入庫記錄:" + check2.get("msg"));
            result.put("apiStatus", false);
            loggingDao.wrtieLog("1", apiPath + "/purchaseStorageReturnV2", JSON.toJSONString(requestParams), JSON.toJSONString(result));
            return result;
        }
         */

        RecordSetTrans set = new RecordSetTrans();//更新仓库库存何报废资产
        set.setAutoCommit(false);

        String main_sql = "insert into uf_003_yyArrivalRecord"
                + "(formmodeid,modedatacreater,modedatacreatertype,modedatacreatedate,modedatacreatetime,MODEUUID"
                + ",eapItemCode,itemcode,assetName,assetDescribe,unit,isAsset,manageDep,assetModel,assetType,quantity,locationCode,locationDescribe"
                + ",brand,manufacturer,FACode,FACategory,prjNo,poCode,price,arrivalDate,supplier,assetNums,thisSouce,prid,dateStr,wereHouse,currency," +
                "params_id,detail_id)"
                + "values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";

        String sql_1 = "update " + assetTable + " set totalQuantity=totalQuantity-?,InventoryQuantity=InventoryQuantity-? where " + tableKey + "=?";

        List<List<Object>> paramsList_1 = new ArrayList<>();//不是资产
        List<Map<String, String>> logList = new ArrayList<>();
        RecordSet checkPO = new RecordSet();
        RecordSet checkPR = new RecordSet();
        RecordSet checkNums = new RecordSet();
        RecordSet newRs = new RecordSet();
        RecordSet get = new RecordSet();

        String uf_003_yyArrivalRecord_Modeid = getPropValue("SW003", "uf_003_yyArrivalRecord_Modeid");

        String martix = getPropValue("SW003", "martix");

        List<List<Object>> paramsList_main = new ArrayList<>();

        //2023年10月11日改 处理差异数据
        //先根据billid查询OA中是否存在记录
        //List<String> histryid1 = getHistryid1(billid);
        List<String> histryid2 = getHistryid2CGTH(billid);
        if(histryid2.size()>0){
            //备份 用于获取最终的差异detial_id
            List<String> bakDetilsid = allDetailid;//当前的数据
            List<String> bakHistryid2 = histryid2;

            List<String> subList2 = bakHistryid2.stream().filter(p -> bakDetilsid.contains((String) p)).collect(Collectors.toList());
            bakDetilsid.removeAll(subList2);
            bakHistryid2.removeAll(subList2);
            bakDetilsid.addAll(bakHistryid2);//差异数据，包含了新数据

            for(String detail_id : bakDetilsid){
                log.writeLog("存在差异数据，detailid："+detail_id);
                //根据detail_id查询采购入库记录,如果存在则入库后删除记录
                checkPO.execute("select id,eapitemcode,itemcode,assetNums,quantity  from uf_003_yyArrivalRecord where detail_id='"+detail_id+"'");
                if(checkPO.next()){
                    log.writeLog("根据detail_id查询采购退库记录存在,存在则删除记录");
                    String itemid = checkPO.getString("eapitemcode");//物料数据id
                    Double _quantity = checkPO.getDouble("quantity");//采購入庫數量
                    int recordId = checkPO.getInt("id");

                    Map<String,String> assetInfo  = dbTools.getAssetAllFieldoByID(newRs,itemid);
                    String assetCode = assetInfo.get("assetcode");

                    Map<String, String> prInfo = null;
                    String prid = "";
                    for(Map<String,String> map :datas){
                        //获取该assetCode的prid
                        if(map.get("assetCode").equals(assetCode)){
                            prid = map.get("prid").replace("\"","");
                            break;
                        }
                    }
                    //获取pr信息中的仓库
                    if(!prid.isEmpty()){
                        checkPR.execute("select requestid,id from "+prTable+" where requestid="+prid);
                        log.writeLog("select requestid,id from "+prTable+" where requestid="+prid);
                        if(checkPR.next()){
                            prInfo = mainDao.getField1ByPrid(prid,prTable,itemid);
                        }
                    }
                    String wareHouse = (prid.isEmpty() || prInfo == null)  ? assetInfo.get("warehouse") : prInfo.get("field1") ;//存的是倉庫id
                    wareHouse = wareHouse.isEmpty() ? assetInfo.get("warehouse") : wareHouse;
                    //刪除采购記錄--先插入
                    String insertSql = "insert into uf_003_Arrival_del(oldid,eapItemCode,itemcode,assetDescribe,isAsset,quantity,assetModel,manageDep,assetType,locationCode,\n" +
                            "locationDescribe,brand,manufacturer,FACode,FACategory,prjNo,poCode,price,arrivalDate,supplier,thisSouce,assetNums,assetName)\n" +
                            "select id,eapItemCode,itemcode,assetDescribe,isAsset,quantity,assetModel,manageDep,assetType,locationCode,\n" +
                            "locationDescribe,brand,manufacturer,FACode,FACategory,prjNo,poCode,price,arrivalDate,supplier,thisSouce,assetNums,assetName\n" +
                            "from uf_003_yyArrivalRecord where id=" + recordId;
                    set.execute(insertSql);
                    boolean d1 =  set.execute("delete from uf_003_yyArrivalRecord where id=" + recordId);
                    log.writeLog("刪除采购記錄 "+d1);

                    //減少物料表中的庫存數量
                    String s1 = "update " + assetTable + " set totalQuantity=totalQuantity+"+Math.abs(_quantity)+",InventoryQuantity=InventoryQuantity+"+Math.abs(_quantity)+" where id="+itemid;
                    log.writeLog("處理差异数据-恢复物料表中的庫存數量："+s1);
                    boolean r1 = set.execute(s1);
                    log.writeLog("结果1："+r1);

                    //更新倉庫庫存--減少庫存
                    String sql = "select * from uf_003_WarehouseNum where assetCode="+assetInfo.get("id")+" and wareHouse="+wareHouse;
                    if(get.execute(sql) && get.next()){
                        String wid = get.getString("id");
                        String s = "update uf_003_WarehouseNum set num1=num1 + ("+Math.abs(_quantity)+"),num3=num3+("+Math.abs(_quantity)+") where id="+wid;
                        log.writeLog("處理差异数据-更新倉庫庫存 "+s);
                        boolean f = set.execute(s);
                        log.writeLog("更新結果 "+f);
                        if(!f){
                            set.rollback();
                            result.put("msg", "itemcode["+assetCode+"]采購退货更新倉庫庫存失敗");
                            result.put("apiStatus", false);
                            loggingDao.wrtieLog("1", apiPath + "/purchaseStorageReturnV2", JSON.toJSONString(requestParams), JSON.toJSONString(result));
                            return result;
                        }
                    }else {
                        set.rollback();
                        result.put("msg", "itemcode["+assetCode+"]采購退货查詢倉庫庫存失敗-->EAP未查询到倉庫记录:"+wareHouse);
                        result.put("apiStatus", false);
                        loggingDao.wrtieLog("1", apiPath + "/purchaseStorageReturnV2", JSON.toJSONString(requestParams), JSON.toJSONString(result));
                        return result;
                    }
                    //刪除出入庫記錄
                    boolean d2 = set.execute("delete from uf_003_inventoryLog where detail_id='" + detail_id+"'");
                    log.writeLog("刪除出入庫記錄 "+d2);

                }
                log.writeLog("差異數據處理完成 detail_id："+detail_id);
            }
        }

        for (Map<String, String> data : datas) {
            List<Object> param_1 = new ArrayList<>();
            String detail_id = data.get("detailid");
            String assetCode = data.get("assetCode").trim();
            Map<String,String> assetInfo = dbTools.getAssetAllFieldoByCode(newRs,assetCode);
            log.writeLog("assetInfo>>"+JSONObject.toJSONString(assetInfo));
            String assetName = assetInfo.get("assetname"),
                    assetDescribe = assetInfo.get("assetdescribe"),
                    unit = assetInfo.get("unit"),
                    manageDep = assetInfo.get("managedep"),
                    assetModel = assetInfo.get("assetmodel"),
                    assetType = assetInfo.get("assettype");

            String poNo = data.get("poNo");
            String prid = data.getOrDefault("prid","");

            Double quantity = Math.abs(Double.parseDouble(data.get("quantity")));
            String  locationCode = data.containsKey("locationCode")?data.get("locationCode"):"",
                    locationDescribe = data.containsKey("locationDescribe")?data.get("locationDescribe"):"",
                    brand = data.containsKey("brand")?data.get("brand"):"",
                    manufacturer = data.containsKey("manufacturer")?data.get("manufacturer"):"",
                    FACode = data.containsKey("FACode")?data.get("FACode"):"",
                    FACategory = data.containsKey("FACategory")?data.get("FACategory"):"",
                    prjNo = data.containsKey("prjNo")?data.get("prjNo"):"",
                    price = data.containsKey("price")?data.get("price"):"",
                    arrivalDate = data.containsKey("arrivalDate")?data.get("arrivalDate"):"",
                    supplier = data.containsKey("supplier")?data.get("supplier"):"",
                    currency = data.containsKey("currency")?data.get("currency"):"";
            int isAsset = mainDao.getIsAsset(assetCode, "isAsset");
            String itemid = assetInfo.get("id");//物料数据id
            Map<String, String> prInfo = new HashMap<>();
            if(!prid.isEmpty()){
                prInfo = mainDao.getField1ByPrid(prid,prTable,itemid);
//                if(prInfo == null || prInfo.get("field1").equals("")){
//                    result.put("msg", "prid["+prid+"]申请单中未找到itemcode["+assetCode+"]的倉庫信息");
//                    result.put("apiStatus", false);
//                    loggingDao.wrtieLog("1", apiPath + "/purchaseStorageReturnV2", JSON.toJSONString(requestParams), JSON.toJSONString(result));
//                    return result;
//                }
            }
            log.writeLog("prInfo>>"+JSONObject.toJSONString(prInfo));
            //20221019 增加倉庫邏輯 退庫時根據pr中的倉庫進行倉庫庫存增加
            String wareHouse = (prid.isEmpty() || prInfo==null) ?assetInfo.get("warehouse"):prInfo.get("field1");//存的是倉庫id
            wareHouse = wareHouse.isEmpty() ? assetInfo.get("warehouse") : wareHouse;
            if(wareHouse.isEmpty()){
                result.put("msg", "itemcode["+assetCode+"]采購退庫更新倉庫庫存失敗-->PR["+prid+"]未查找到倉庫(EAP未維護默認倉庫或code與EAP的PR單中不一致)");
                result.put("apiStatus", false);
                loggingDao.wrtieLog("1", apiPath + "/purchaseStorageReturnV2", JSON.toJSONString(requestParams), JSON.toJSONString(result));
                return result;
            }
            //2023年10月11日改
            //根据detail_id查询采购记录,如果存在则判断两次数量差异，不存在走原本逻辑
            detail_id = "CGTH-"+detail_id;
            checkPO.execute("select id,assetNums,quantity from uf_003_yyArrivalRecord where detail_id='"+detail_id+"'");
            if(checkPO.next()) {
                if(isAsset==0){
                    //資產物料 发出提醒
                    get.execute(" select depmanager from "+martix +" where depid="+manageDep);
                    get.next();
                    String depManager = get.getString("depmanager");

                    log.writeLog("发起提醒给到管理部门负责人>"+depManager);
                    SysRemindWorkflow remind = new SysRemindWorkflow();
                    remind.make("采購退庫提醒 "+assetCode,
                            0, 0, 0, 0, 1,
                            depManager+",1",
                            "<span> item code為["+assetCode+"]發生了采購退貨,該item為資產物料,請在系統中做相關處理", 0);
                }
                Double _quantity = Math.abs(checkPO.getDouble("quantity"));//采購入庫數量
                int recordId = checkPO.getInt("id");
                //判断上一次的采购数量和本次数量
                if(quantity>_quantity){
                    String upSql = "update uf_003_yyArrivalRecord set quantity="+("-"+quantity)+" where id="+recordId;
                    log.writeLog("当前退库数量大于上一次的记录数量 更新uf_003_yyArrivalRecord表中的_quantity>> "+upSql);
                    boolean r1 = set.execute(upSql);
                    log.writeLog("更新結果 "+r1);
                }else if(quantity<_quantity){
                    String upSql = "update uf_003_yyArrivalRecord set quantity="+("-"+quantity)+" where id="+recordId;
                    log.writeLog("当前退库数量小于上一次的记录数量 更新uf_003_yyArrivalRecord表中的_quantity>> "+upSql);
                    boolean r2 = set.execute(upSql);
                    log.writeLog("更新結果 "+r2);
                }
            }else{
                //新增采購退貨記錄
                //------分割綫
                List<Object> param_main = new ArrayList<>();
                param_main.add(uf_003_yyArrivalRecord_Modeid);
                param_main.add(1);
                param_main.add(0);
                param_main.add(dateTools.getCurrentDate());
                param_main.add(dateTools.getCurrentTime());
                param_main.add(dateTools.getUUID());
                param_main.add(mainDao.getIsAsset(assetCode, "id"));
                param_main.add(assetCode);
                param_main.add(assetName);
                param_main.add(assetDescribe);
                //param_0.add(getAssetUnit(unit));
                param_main.add(unit);
                param_main.add(isAsset);
                //param_0.add(getManageDep(assetCode, "manageDep"));
                param_main.add(manageDep);
                param_main.add(assetModel);
                //param_0.add(getAssetType(assetType));
                param_main.add(assetType);
                param_main.add("-"+quantity);
                param_main.add(locationCode);
                param_main.add(locationDescribe);
                param_main.add(brand);
                param_main.add(manufacturer);
                param_main.add(FACode);
                param_main.add(FACategory);
                param_main.add(prjNo);
                param_main.add(poNo.replace("\"",""));
                param_main.add(price);
                param_main.add(arrivalDate.replace("/", "-"));
                param_main.add(supplier);
                param_main.add(0);
                param_main.add(2);
                param_main.add(prid);
                param_main.add(dateTools.getCurrentDate());
                param_main.add(wareHouse);
                param_main.add(currency);//2023年8月25日 增加币种
                param_main.add(billid);//2023年10月7日增加
                param_main.add(detail_id);//2023年10月7日增加
                paramsList_main.add(param_main);
                //------分割綫
            }

            //根据detail_id查询出入库记录,如果存在则判断两次数量差异，不存在走原本逻辑(逻辑已在上面处理 这里只需要判断更新库存)
            checkNums.execute("select id,assetCode,quantity from uf_003_inventoryLog where detail_id='"+detail_id+"'");
            if(checkNums.next()) {
                Double thisquantity = Math.abs(checkNums.getDouble("quantity"));
                int recordId = checkNums.getInt("id");
                if(thisquantity!=quantity){
                    String s1 = "update uf_003_inventoryLog set quantity="+("-"+quantity)+" where id="+recordId;
                    log.writeLog("更新出入庫記錄 "+s1);
                    boolean r1 = set.execute(s1);
                    log.writeLog("更新結果 "+r1);

                    //更新倉庫庫存--根據thisquantity和quantity的差額
                    Double chae = quantity-thisquantity;//為負數時需要增加倉庫庫存 正數則減少
                    String sql = "select * from uf_003_WarehouseNum where assetCode="+assetInfo.get("id")+" and wareHouse="+wareHouse;
                    if(get.execute(sql) && get.next()){
                        String wid = get.getString("id");
                        String sql1 = "";
                        String sql2 = "";
                        if(chae>0){
                            sql1 = "update uf_003_WarehouseNum set num1=num1 - "+chae+",num3=num3 - "+chae+" where id="+wid;
                            sql2 = "update " + assetTable + " set totalQuantity=totalQuantity-"+chae+",InventoryQuantity=InventoryQuantity-"+chae+" where id="+itemid;
                        }else{
                            sql1 = "update uf_003_WarehouseNum set num1=num1 + "+Math.abs(chae)+",num3=num3 + "+Math.abs(chae)+" where id="+wid;
                            sql2 = "update " + assetTable + " set totalQuantity=totalQuantity+"+Math.abs(chae)+",InventoryQuantity=InventoryQuantity+"+Math.abs(chae)+" where id="+itemid;
                        }

                        log.writeLog("有倉庫庫存-更新倉庫庫存 "+sql1);
                        boolean f1 = set.execute(sql1);
                        log.writeLog("結果1 "+f1);

                        //減少物料表中的庫存數量
                        log.writeLog("删除差异数据-更新物料表中的庫存數量："+sql2);
                        boolean f2 = set.execute(sql2);
                        log.writeLog("结果2："+f2);

                        if(!f1 || !f2){
                            set.rollback();
                            result.put("msg", "itemcode["+assetCode+"]采購入庫更新倉庫庫存失敗");
                            result.put("apiStatus", false);
                            loggingDao.wrtieLog("1", apiPath + "/purchaseStorageReturnV2", JSON.toJSONString(requestParams), JSON.toJSONString(result));
                            return result;
                        }
                    }else {
                        set.rollback();
                        result.put("msg", "itemcode["+assetCode+"]采購入庫查詢倉庫庫存失敗-->EAP未查询到倉庫记录:"+wareHouse);
                        result.put("apiStatus", false);
                        loggingDao.wrtieLog("1", apiPath + "/purchaseStorageReturnV2", JSON.toJSONString(requestParams), JSON.toJSONString(result));
                        return result;
                    }
                }
            } else{
                String sql = "select * from uf_003_WarehouseNum where assetCode="+assetInfo.get("id")+" and wareHouse="+wareHouse;
                if(get.execute(sql) && get.next()){
                    String wid = get.getString("id");
                    boolean f = set.execute("update uf_003_WarehouseNum set num1=num1-("+quantity+"),num3=num3-("+quantity+") where id="+wid);
                    if(!f){
                        set.rollback();
                        result.put("msg", "itemcode["+assetCode+"]采購退庫更新倉庫庫存失敗");
                        result.put("apiStatus", false);
                        loggingDao.wrtieLog("1", apiPath + "/purchaseStorageReturnV2", JSON.toJSONString(requestParams), JSON.toJSONString(result));
                        return result;
                    }
                }else{
                    set.rollback();
                    result.put("msg", "itemcode["+assetCode+"]未查詢到EAP中的倉庫庫存記錄");
                    result.put("apiStatus", false);
                    loggingDao.wrtieLog("1", apiPath + "/purchaseStorageReturnV2", JSON.toJSONString(requestParams), JSON.toJSONString(result));
                    return result;
                }

                Map<String, String> logMap = new HashMap();
                logMap.put("assetCode", assetCode);
                logMap.put("assetName", assetInfo.get("assetname"));
                logMap.put("quantity", "-"+String.valueOf(Math.abs(quantity)));//采购退货显示-
                logMap.put("requestNumber", "退貨-" + poNo);
                logMap.put("reason", "退貨");
                logMap.put("field1", wareHouse);
                logMap.put("field2", prInfo.get("field2"));
                logMap.put("detail_id",detail_id);
                logList.add(logMap);

                //減少物料表中的庫存數量
                param_1.add(quantity);
                param_1.add(quantity);
                param_1.add(assetCode);
                paramsList_1.add(param_1);
            }

        }

        if (paramsList_main.size() > 0) {
            try {
                log.writeLog("退库生成采購記錄中");
                log.writeLog(JSONObject.toJSONString(paramsList_main));
                set.executeBatchSql(main_sql, paramsList_main);
            } catch (Exception e) {
                set.rollback();
                e.printStackTrace();
                result.put("msg", "退库生成采購記錄中執行SQL異常 \n" + e.getMessage());
                result.put("apiStatus", false);
                loggingDao.wrtieLog("1", apiPath + "/purchaseStorageReturnV2", JSON.toJSONString(requestParams), JSON.toJSONString(result));
                return result;
            }
        }
        if (paramsList_1.size() > 0) {
            try {
                log.writeLog("退库減少物料表中的庫存數量");
                log.writeLog(JSONObject.toJSONString(paramsList_1));
                log.writeLog(sql_1);
                set.executeBatchSql(sql_1, paramsList_1);
            } catch (Exception e) {
                set.rollback();
                e.printStackTrace();
                result.put("msg", "退库減少物料表中的庫存數量執行SQL異常 \n" + e.getMessage());
                result.put("apiStatus", false);
                loggingDao.wrtieLog("1", apiPath + "/purchaseStorageReturnV2", JSON.toJSONString(requestParams), JSON.toJSONString(result));
                return result;
            }
        }


        try{
            loggingDao.wrtieLog("1", apiPath + "/purchaseStorageReturnV2", JSON.toJSONString(requestParams), JSON.toJSONString(result));
            for (int i = 0; i < logList.size(); i++) {
                Map<String, String> log = logList.get(i);
                loggingDao.wrtieInventoryLog(set,"1", log.get("assetCode"),
                        Double.parseDouble(log.get("quantity")), log.get("requestNumber"),
                        log.get("reason"),log.get("field1"),log.get("field2"),
                        "3","","",log.get("assetName"),billid,log.get("detail_id"));
            }
        }catch (Exception e){
            set.rollback();
            e.printStackTrace();
            result.put("msg", "采購退庫最终记录日志异常 \n" + e.getMessage());
            result.put("apiStatus", false);
            return result;
        }

        set.commit();
        return result;
    }

    /**
     * 根据billid获取采购入库表中的记录
     * @param params_id
     * @return
     */
    public List<String> getHistryid1(String params_id){
        List<String> ids = new ArrayList<>();
        RecordSet rs = new RecordSet();
        rs.execute("select detail_id from uf_003_yyArrivalRecord where params_id='"+params_id+"'");
        while (rs.next()){
            ids.add(rs.getString("detail_id"));
        }
        return ids;
    }

    /**
     * 根据billid获取出入库记录表中的记录
     * @param params_id
     * @return
     */
    public List<String> getHistryid2CGRK(String params_id){
        List<String> ids = new ArrayList<>();
        RecordSet rs = new RecordSet();
        rs.execute("select detail_id from uf_003_inventoryLog where params_id='"+params_id+"'");
        while (rs.next()){
            ids.add(rs.getString("detail_id"));
        }
        return ids;
    }

    public List<String> getHistryid2CGTH(String params_id){
        List<String> ids = new ArrayList<>();
        RecordSet rs = new RecordSet();
        rs.execute("select detail_id from uf_003_inventoryLog where params_id='"+params_id+"'");
        while (rs.next()){
            ids.add(rs.getString("detail_id"));
        }
        return ids;
    }
}
